package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.prefs.BackingStoreException;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) throws BackingStoreException {
        log.info("[预约设置-上传]fileName:{},size:{}",multipartFile.getOriginalFilename(),multipartFile.getSize());
        //获取上传文件名字
        String filename = multipartFile.getOriginalFilename();
        //判断是否传入文件
        if (StringUtils.isEmpty(filename)) {
            return new Result(false,"缺少文件名");
        }
        Workbook workbook = null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputStream);
            }else if (filename.endsWith(".xlsx")){
                workbook = new XSSFWorkbook(inputStream);
            }else {
                return new Result(false,"文件格式不正确");
            }
        } catch (IOException e) {
            log.error("",e);
            return new Result(false,"上传文件失败");
        }
        //遍历excel表取出数据
        ArrayList<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet sheet : workbook) {
            //0行为表头,忽略
            for (int i = 1;i <= sheet.getLastRowNum();i++){//sheet.getLastRowNum()  获取最后一行
                //获取第一行
                Row row = sheet.getRow(i);
                //解析处理特殊数据
                OrderSetting orderSetting = parseOrderSetting(row);
                //加入列表
                orderSettings.add(orderSetting);
            }
        }
        log.info("[预约设置-上传]解析成功,result:{}",orderSettings);

        //调用数据入库
        orderSettingService.addAll(orderSettings);
        return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    //解析处理特殊数据
    private OrderSetting parseOrderSetting(Row row) throws BackingStoreException {
        Date data = null;
        Integer number = null;
        try {
            //获取日期
            if (row.getCell(0)!=null) {
                data = row.getCell(0).getDateCellValue();
            }
            //获取最大预约数量
            if (row.getCell(1)!=null) {
                double numberValue = row.getCell(1).getNumericCellValue();
                number = Double.valueOf(numberValue).intValue();
            }
        } catch (Exception e) {
            log.error("",e);
            throw new BackingStoreException(String.format("数据格式错误,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        //判断是否缺少数据
        if (data == null || number ==null) {
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        return new OrderSetting(data,number);
    }


    //根据月份查询对应预约数据
    @GetMapping("getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam Integer year, @RequestParam Integer month){
        log.info("[预约设置-月份查询]年:{},月:{}",year,month);

        List<OrderSetting> orderSettings  = orderSettingService.getOrderSettingByMonth(year,month);
        //转换结构
        List<Map<String,Object>> voList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings){
            //创建用于日期处理的工具类Claendar对象
            Calendar cal = Calendar.getInstance();
            //设置时间为预约日期
            cal.setTime(orderSetting.getOrderDate());
            Map<String,Object> map = new HashMap<>();
            //设置日期限-当月第几天
            map.put("date",cal.get(Calendar.DAY_OF_MONTH));
            //设置数量-当天允许的预约数量
            map.put("number",orderSetting.getNumber());
            //设置已经预约的人数
            map.put("reservations",orderSetting.getReservations());
            voList.add(map);
        }
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS,voList);
    }

    //根据日期编辑
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        log.info("[预约设置-根据日期编辑]data:{}",orderSetting);

        orderSettingService.editNumberByDate(orderSetting.getOrderDate(),orderSetting.getNumber());

        return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
    }
}
